package com.mspbots.core.wise.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mspbots.core.AbstractBaseServiceImpl;
import com.mspbots.core.wise.mapper.TenantRuleMapper;
import com.mspbots.core.wise.model.TenantRule;
import com.mspbots.core.wise.service.TenantRuleService;
import com.mspbots.cw.request.EscalationDTO;
import com.mspbots.cw.request.TenantRuleDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class TenantRuleServiceImpl extends AbstractBaseServiceImpl<TenantRuleMapper, TenantRule> implements TenantRuleService {


    @Override
    public List<TenantRuleDTO> listAnalysis(TenantRule query) {
        return this.baseMapper.listAnalysis(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveBatch(Long tenantId, long[] ruleIds) {
        QueryWrapper delQuery = new QueryWrapper();
        delQuery.eq("tenant_id", tenantId);
        this.baseMapper.delete(delQuery);
        if (ruleIds != null && ruleIds.length > 0) {
            List<TenantRule> list = new ArrayList<>();
            for (Long ruleId : ruleIds) {
                TenantRule tenantRule = new TenantRule();
                tenantRule.setRuleId(ruleId);
                tenantRule.setTenantId(tenantId);
                list.add(tenantRule);
            }
            return saveBatch(list);
        }
        return true;
    }

    @Override
    public IPage<TenantRuleDTO> pageDetail(Page<TenantRuleDTO> page, TenantRuleDTO queryParams) {
//        QueryWrapper<TenantRuleDTO> queryWrapper = new QueryWrapper<>(queryParams);
//        page.addOrder(OrderItem.desc("id"));
//        IPage iPage = baseMapper.selectPage(page, queryWrapper);
//        List<TenantRule> records = iPage.getRecords();
//        for (TenantRule tenantRule : records) {
//
//        }

        return baseMapper.pageDetail(page, queryParams);
    }

    @Override
    public TenantRuleDTO detail(TenantRuleDTO query) {
        return baseMapper.detail(query);
    }

    @Override
    public List<TenantRuleDTO> getEscalation(TenantRuleDTO query) {
        return baseMapper.getEscalation(query);
    }

    @Override
    public List<EscalationDTO> selectEscalationParams(EscalationDTO query) {
        return baseMapper.selectEscalationParams(query);
    }

    @Override
    public List<TenantRule> selectByTenantId(Long tenantId) {
        QueryWrapper<TenantRule> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id", tenantId);
        return this.baseMapper.selectList(queryWrapper);
    }


}
